package com.web44.ssm.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;

/**
 * @Title: ErrorInterceptor
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2024/2/18 13:59
 */
@Component
public class ErrorInterceptor implements HandlerInterceptor {


    /**
     * 当前的请求  是resultful 风格的 还是非resultful  风格的
     *    resultful  类上 RestController
     *               方法上 reponsebody 注解
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if(!(handler instanceof HandlerMethod)) {
             return true;
        }

        HandlerMethod hm = (HandlerMethod)handler;

        Method method = hm.getMethod();
        Class<?> beanType = hm.getBeanType();

        boolean isJson = method.isAnnotationPresent(ResponseBody.class) || beanType.isAnnotationPresent(RestController.class);
        request.setAttribute("isJson",isJson);

        return true;

    }
}
